<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大迁视界 - Odyssey Of Wildlife</title>
    <script src="../libs/Cesium/Cesium.js"></script>
    <link href="../libs/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        header {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            padding: 20px 50px;
            background-color: rgba(255, 255, 200, 0);
            position: relative;
            z-index: 10;
        }

        .logo {
            display: flex;
            align-items: center;
        }

        .logo img {
            height: 40px;
            margin-right: 10px;
        }

        .logo span {
            font-size: 18px;
            font-weight: bold;
            color: #febf66;
        }

        nav ul {
            display: flex;
            list-style: none;
            margin-left: 20px;
        }

        nav ul li {
            margin: 0 15px;
        }

        nav ul li a {
            text-decoration: none;
            color: #54251e;
            font-weight: 500;
            padding: 5px 0;
            transition: color 0.3s;
        }

        nav ul li a:hover, nav ul li a.active {
            color: #febf66;
            font-weight: bold;
        }

        .user-actions {
            display: flex;
            align-items: center;
            margin-left: auto;
        }

        .profile-btn {
            display: flex;
            align-items: center;
            margin-right: 20px;
            text-decoration: none;
            color: #eb9b3e;
            background-color: #fff;
            padding: 5px 10px;
            border-radius: 5px;
            transition: background-color 0.3s;
            font-weight: bold;
        }

        .login-btn {
            background-color: #eb9b3e;
            color: white;
            padding: 6px 10px;
            border-radius: 5px;
            text-decoration: none;
            transition: background-color 0.3s;
            font-weight: bold;
        }

        .login-btn:hover {
            background-color: #FF7F00;
        }

        html, body, #cesium_container {
            margin: 0;
            padding: 0;
            height: 100vh;
        }
        #cesium_container {
            height: 95vh;
        }
        .up_track{
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            text-decoration: none;
            color: white;
            background-color: #5cb85c;
            transition: background-color 0.3s;
            font-weight: bold;
            margin-right: 15px;
        }
       .up_photo{
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            text-decoration: none;
            color: white;
            background-color: #007bff;
            transition: background-color 0.3s;
            font-weight: bold;
        }
        .user-actions img{
            height: 20px;
            margin-right: 10px;
        }
        .map-buttons {
            position: absolute;
            right: 20px;
            top: 200px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 1000;
        }
        /* 弹窗 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            max-width: 500px;
            border-radius: 5px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }
        .input-group {
            margin-bottom: 15px;
        }
        .input-group label {
            display: block;
            margin-bottom: 5px;
        }
        .input-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .loading {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 24px;
        color: #333;
        z-index: 2000;
        }
    </style>
</head>

<body>
    <header>
        <div class="logo">
            <img src="../../../css/src/md-pets@1x.png" alt="Logo">
            <span>odyssey of wildlife</span>
        </div>
        <nav>
            <ul>
                <li><a href="./Cesium1.html" class="active">开始</a></li>
                <li><a href="./Cesium1.html">科普展示</a></li>
                <li><a href="#">互动游戏</a></li>
                <li><a href="../../../Knowledge_git/homepage.html">科学知识库</a></li>
                <li><a href="#">关于我们</a></li>
            </ul>
        </nav>
        <div class="user-actions">
            <a href="#" class="profile-btn" id="profileButton">
                <img src="../../../css/src/user-icon.png" alt="User">
                <span>个人主页</span>
            </a>
            <a href="../../../login.html" class="login-btn">Login / Register</a>
        </div>
    </header>
    <div id="cesium_container">
        <div class="loading" id="loading">加载中...</div>
        <div class="map-buttons">
            <a href="javascript:void(0)" class="login-btn" id="openModalBtn"style="background-color:#5cb85c;">
                轨迹上传
            </a>
            <a href="javascript:void(0)" class="login-btn" id="openImageModalBtn" style="background-color:#007bff;">
                上传拍照点位
            </a>
            <select class="species-select" id="speciesSelect">
                <option value="" disabled selected>选择物种</option>
                <option value="test">黑翅长脚鹬</option>
                <option value="zebra">斑马</option>
                <option value="species3">反嘴鹬</option>
                <option value="species4">角马</option>
            </select>
        </div>
         <!-- 上传图片和地理信息的模态框 -->
    <div id="uploadImageModal" class="modal">
        <div class="modal-content">
            <span class="close" id="closeImageModal">&times;</span>
            <h2>上传图片并输入地理信息</h2>
            <div class="input-group">
                <label for="fileInput">选择图片：</label>
                <input type="file" id="fileInput" accept="image/*">
            </div>
            <div class="input-group">
                <label for="latitudeInput">经度：</label>
                <input type="text" id="latitudeInput" placeholder="请输入经度">
            </div>
            <div class="input-group">
                <label for="longitudeInput">纬度：</label>
                <input type="text" id="longitudeInput" placeholder="请输入纬度">
            </div>
            <button class="btn" id="uploadImageBtn">上传</button>
        </div>
    </div>

    <!-- 上传 CSV 文件的模态框 -->
    <div id="uploadCsvModal" class="modal">
        <div class="modal-content">
            <span class="close" id="closeCsvModal">&times;</span>
            <h2>上传 CSV 文件</h2>
            <form id="csvUploadForm">
                <div class="input-group">
                    <label for="speciesName">物种名称：</label>
                    <input type="text" id="speciesName" name="speciesName" required>
                </div>
                <div class="input-group">
                    <label for="csvFile">选择 CSV 文件：</label>
                    <input type="file" id="csvFile" name="csvFile" accept=".csv" required>
                </div>
                <br><br>
                <button type="submit" class="btn">上传并导入数据库</button>
            </form>
            <div id="csvMessage"></div>
        </div>
    </div>
    </div>
    鼠标移动的经纬度：<span id='movePosition'></span>
    <br/>
    鼠标点击的经纬度：<span id='clickPosition'>

    </span>

    <script type="text/javascript">
        const loadingElement = document.getElementById('loading');
        const speciesSelect = document.getElementById('speciesSelect');

        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNTliNDE3MC05NDE0LTRhOTMtODIwYi0yZjMxZjVlZjNkMDIiLCJpZCI6MjkwMTk0LCJpYXQiOjE3NDc2MzYwMTV9.SPGLHdzH1zgco8PydI7KBFEsIsmicw8ZFw4gE3Ch-8w'

        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(30,-10,40,10)

        const viewer = new Cesium.Viewer('cesium_container',{
            animation:false,//动画控件
            baseLayerPicker:true,//底图切换控件
            fullscreenButton:false,//全屏控件
            timeline:false,//时间轴控件
            homeButton:false,//home键
            sceneModePicker:true,//2维3维场景切换控件
            navigationHelpButton: false,//help控件
            geocoder: false,//搜索控件和底下文字
            infoBox:false,//弹出框
            selectionIndicator: false//绿色选中框
        })

        // 去除logo
        viewer._cesiumWidget._creditContainer.style.display = "none";

        // // 切换到2D平面模式
        // viewer.scene.mode = Cesium.SceneMode.SCENE2D;       

        // // 设置俯视视角（-90度俯角）
        // viewer.camera.setView({
        //   destination: Cesium.Cartesian3.fromDegrees(117.134, 32.726, 10000000),
        //   orientation: {
        //     heading: Cesium.Math.toRadians(0),
        //     pitch: Cesium.Math.toRadians(-90),
        //     roll: 0
        //   }
        // });

        //鼠标移动和点击显示经纬度
        let mouseMovePositionSpan = document.getElementById('movePosition')
        let mouseClickPositionSpan = document.getElementById('clickPosition')
        addmouseClickEvent(viewer, mouseClickPositionSpan)
        addmouseMoveEvent(viewer, mouseMovePositionSpan)

        //绑定鼠标事件，点击获取经纬度
        function addmouseClickEvent(viewer, div) {
            let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            //监听鼠标点击,拿到坐标点位置
            handler.setInputAction(function (event) {
                // 转换为不包含地形的笛卡尔坐标
                // 注意下面这句话与鼠标移动不同
                let position = viewer.scene.camera.pickEllipsoid(event.position);
                if(!position) return
                // 转经纬度（弧度）坐标
                let radiansPos = Cesium.Cartographic.fromCartesian(position);      
                //转为经纬度
                let pickedFeature = viewer.scene.pick(event.position);
                let x  = Cesium.Math.toDegrees(radiansPos.longitude) - 0
                let y  = Cesium.Math.toDegrees(radiansPos.latitude) - 0
                // console.log(x,y)
                div.innerHTML = `${x.toFixed(3)},${y.toFixed(3)}`
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }
        //绑定鼠标事件，移动获取经纬度
        function addmouseMoveEvent(viewer, div) {
            let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            //监听鼠标点击,拿到坐标点位置
            handler.setInputAction(function (event) {
                // 转换为不包含地形的笛卡尔坐标
                // 注意下面这句话与鼠标点击不同
                let position = viewer.scene.camera.pickEllipsoid(event.endPosition);
                if(!position) return
                // 转经纬度（弧度）坐标
                let radiansPos = Cesium.Cartographic.fromCartesian(position);      
                //转为经纬度
                let x  = Cesium.Math.toDegrees(radiansPos.longitude) - 0
                let y  = Cesium.Math.toDegrees(radiansPos.latitude) - 0
                div.innerHTML = `${x.toFixed(3)},${y.toFixed(3)}`
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }

        // 动物迁徙数据配置
        const animalData = {
            zebra: {
                color: Cesium.Color.RED.withAlpha(0.8),
                url: 'zebra.html',
                specialPoint: Cesium.Cartesian3.fromDegrees(34.712, -2.250), // 新增斑马特殊点坐标
                positions: [
                    Cesium.Cartesian3.fromDegrees(34.502, -3.7291),
                    Cesium.Cartesian3.fromDegrees(34.4174, -3.5315),
                    Cesium.Cartesian3.fromDegrees(34.4732, -3.1645),
                    Cesium.Cartesian3.fromDegrees(34.451, -2.9463),
                    Cesium.Cartesian3.fromDegrees(34.4721, -2.9074),
                    Cesium.Cartesian3.fromDegrees(34.601, -2.25),
                    Cesium.Cartesian3.fromDegrees(34.745, -2.05),
                    Cesium.Cartesian3.fromDegrees(34.705, -1.833),
                    Cesium.Cartesian3.fromDegrees(34.79, -1.796),
                    Cesium.Cartesian3.fromDegrees(34.644, -2.396),
                    Cesium.Cartesian3.fromDegrees(34.522, -2.875),
                    Cesium.Cartesian3.fromDegrees(34.475, -3.746)
                ]
            },
            // avocet: {
            //     color: Cesium.Color.BLUE.withAlpha(0.8),
            //     url: 'avocet.html',
            //     specialPoint: Cesium.Cartesian3.fromDegrees(120.462,31.338), // 新增反嘴鹬特殊点坐标
            //     positions: [
            //         Cesium.Cartesian3.fromDegrees(110.234, 20.393),
            //         Cesium.Cartesian3.fromDegrees(110.458, 19.462),
            //         Cesium.Cartesian3.fromDegrees(109.958, 21.823),
            //         Cesium.Cartesian3.fromDegrees(112.993, 28.968),
            //         Cesium.Cartesian3.fromDegrees(124.669, 47.163),
            //         Cesium.Cartesian3.fromDegrees(125.615, 46.511),
            //         Cesium.Cartesian3.fromDegrees(124.801, 44.344),
            //         Cesium.Cartesian3.fromDegrees(115.33, 38.076),
            //         Cesium.Cartesian3.fromDegrees(116.86, 29.621),
            //         Cesium.Cartesian3.fromDegrees(117.985, 26.649),
            //         Cesium.Cartesian3.fromDegrees(111.009, 21.899),
            //         Cesium.Cartesian3.fromDegrees(110.338, 21.558)
            //     ]
            // },
            stilt: {
                color: Cesium.Color.GREEN.withAlpha(0.8),
                url: '../../../3Dsection/hello.html',
                specialPoint: Cesium.Cartesian3.fromDegrees(102.997,17.071), // 新增黑翅长脚鹬特殊点坐标
                positions: [
                    Cesium.Cartesian3.fromDegrees(106.584, 20.848),
                    Cesium.Cartesian3.fromDegrees(110.622, 21.495),
                    Cesium.Cartesian3.fromDegrees(120.071, 32.034),
                    Cesium.Cartesian3.fromDegrees(118.764, 37.675),
                    Cesium.Cartesian3.fromDegrees(116.84, 43.232),
                    Cesium.Cartesian3.fromDegrees(123.516, 46.069),
                    Cesium.Cartesian3.fromDegrees(124.209, 47.236),
                    Cesium.Cartesian3.fromDegrees(123.549, 47.094),
                    Cesium.Cartesian3.fromDegrees(119.667, 39.325),
                    Cesium.Cartesian3.fromDegrees(107.637, 21.74),
                    Cesium.Cartesian3.fromDegrees(118.215, 26.31),
                    Cesium.Cartesian3.fromDegrees(101.854, 12.999)
                ]
            },
            wildebeest: {
                color: Cesium.Color.ORANGE.withAlpha(0.8),
                url: 'hello.html',
                specialPoint: Cesium.Cartesian3.fromDegrees(34.148,-2.792), // 新增角马特殊点坐标
                positions: [
                    Cesium.Cartesian3.fromDegrees(34.5001, -3.7654),
                    Cesium.Cartesian3.fromDegrees(34.1119, -3.7578),
                    Cesium.Cartesian3.fromDegrees(33.9563, -3.7012),
                    Cesium.Cartesian3.fromDegrees(33.8153, -3.6563),
                    Cesium.Cartesian3.fromDegrees(33.7893, -3.5986),
                    Cesium.Cartesian3.fromDegrees(33.5563, -2.9564),
                    Cesium.Cartesian3.fromDegrees(33.8963, -1.9782),
                    Cesium.Cartesian3.fromDegrees(33.9987, -1.5651),
                    Cesium.Cartesian3.fromDegrees(34.4125, -2.0548),
                    Cesium.Cartesian3.fromDegrees(34.7563, -2.5637),
                    Cesium.Cartesian3.fromDegrees(34.7101, -3.0456),
                    Cesium.Cartesian3.fromDegrees(34.5111, -3.6567)
                ]
            },
            robin: {
                color: Cesium.Color.PURPLE.withAlpha(0.8),
                url: 'robin.html',
                specialPoint: Cesium.Cartesian3.fromDegrees(-85.197,34.032), // 新增美洲知更鸟特殊点坐标
                positions: [
                    Cesium.Cartesian3.fromDegrees(-84.153, 22.295),
                    Cesium.Cartesian3.fromDegrees(-81.472, 26.196),
                    Cesium.Cartesian3.fromDegrees(-77.935, 35.916),
                    Cesium.Cartesian3.fromDegrees(-76.235, 42.996),
                    Cesium.Cartesian3.fromDegrees(-76.029, 45.948),
                    Cesium.Cartesian3.fromDegrees(-80.694, 45.9),
                    Cesium.Cartesian3.fromDegrees(-75.943, 45.937),
                    Cesium.Cartesian3.fromDegrees(-84.227, 41.886),
                    Cesium.Cartesian3.fromDegrees(-86.326, 37.257),
                    Cesium.Cartesian3.fromDegrees(-90.495, 30.859),
                    Cesium.Cartesian3.fromDegrees(-97.468, 26.035),
                    Cesium.Cartesian3.fromDegrees(-101.702, 19.167)
                ]
            }
        };

        // 创建实体集合（包含点和线）
        const entities = {};
        Object.keys(animalData).forEach(animal => {
            entities[animal] = {
                points: [],
                lines: []
            };
            
            // 创建特殊跳转点实体（角马、斑马、反嘴鹬、黑翅长脚鹬、美洲知更鸟）
            if (animal === 'wildebeest' || animal === 'zebra' || animal === 'avocet' || animal === 'stilt' || animal === 'robin') {
                const pointConfig = {
                    pixelSize: 16,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 4,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    scaleByDistance: new Cesium.NearFarScalar(1.5e2, 2.0, 8.0e6, 0.5)
                };

                if (animal === 'wildebeest') {
                    pointConfig.color = new Cesium.ColorMaterialProperty(
                        new Cesium.CallbackProperty(function() {
                            return Cesium.Color.fromHsl(
                                (Date.now() % 3000) / 3000,
                                1.0, 
                                0.5,
                                0.9
                            );
                        }, false)
                    );
                } else if (animal === 'zebra') {
                    pointConfig.color = new Cesium.ColorMaterialProperty(
                        new Cesium.CallbackProperty(function() {
                            return Cesium.Color.fromBytes(
                                Math.sin(Date.now()*0.002)*127+128,
                                Math.cos(Date.now()*0.003)*127+128,
                                128,
                                200
                            );
                        }, false)
                    );
                    pointConfig.pixelSize = 18;
                    pointConfig.outlineWidth = 5;
                } else if (animal === 'avocet') {
                    pointConfig.color = new Cesium.ColorMaterialProperty(
                        new Cesium.CallbackProperty(function() {
                            return Cesium.Color.fromHsl(
                                (Date.now() % 3000) / 3000,
                                1.0, 
                                0.5,
                                0.9
                            );
                        }, false)
                    );
                }else if (animal === 'stilt') {
                    pointConfig.color = new Cesium.ColorMaterialProperty(
                        new Cesium.CallbackProperty(function() {
                            return Cesium.Color.fromHsl(
                                (Date.now() % 3000) / 3000,
                                1.0, 
                                0.5,
                                0.9
                            );
                        }, false)
                    );
                }else if (animal === 'robin') {
                    pointConfig.color = new Cesium.ColorMaterialProperty(
                        new Cesium.CallbackProperty(function() {
                            return Cesium.Color.fromHsl(
                                (Date.now() % 3000) / 3000,
                                1.0, 
                                0.5,
                                0.9
                            );
                        }, false)
                    );
                }

            // 添加视频播放实体点
            if (animal === 'wildebeest') {
                // 第一个视频点 (34.590,-2.316)
                // entities[animal].videoPoint = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(34.590,-2.316),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频1'
                // });

                // // 第二个视频点 (33.897,-3.691)
                // entities[animal].videoPoint2 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(33.897, -3.691),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频2'
                // });

                // // 第三个视频点 (33.800,-3.626)
                // entities[animal].videoPoint3 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(33.800, -3.626),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频3'
                // });

                // // 第四个视频点 (33.560,-2.968)
                // entities[animal].videoPoint4 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(33.560, -2.968),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频4'
                // });

                // // 第五个视频点 (33.697,-2.550)
                // entities[animal].videoPoint5 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(33.697,-2.550),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频5'
                // });

                // // 第六个视频点 (33.885,-2.006)
                // entities[animal].videoPoint6 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(33.885,-2.006),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频6'
                // });

                // // 第七个视频点 (117.324,28.497)
                // entities[animal].videoPoint7 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(117.324,28.497),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频7'
                // });

                // // 第八个视频点 (104.822,17.962)
                // entities[animal].videoPoint8 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(104.822,17.962),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频8'
                // });

                // // 第九个视频点 (-88.420,34.166)
                // entities[animal].videoPoint9 = viewer.entities.add({
                //     position: Cesium.Cartesian3.fromDegrees(-88.420,34.166),
                //     point: {
                //         pixelSize: 14,
                //         color: Cesium.Color.CYAN.withAlpha(0.8),
                //         outlineColor: Cesium.Color.WHITE,
                //         outlineWidth: 3,
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         disableDepthTestDistance: Number.POSITIVE_INFINITY
                //     },
                //     description: '点击播放视频8'
                // });
            }

            entities[animal].jumpPoint = viewer.entities.add({
                position: animalData[animal].specialPoint,
                    point: pointConfig,
                    description: '点击跳转到详细页面'
                });
            }
            
            // 创建普通点实体
            animalData[animal].positions.forEach(position => {
                entities[animal].points.push(viewer.entities.add({
                    position: position,
                    point: {
                        pixelSize: 8,
                        color: animalData[animal].color
                    }
                }));
            });

            // 创建线实体（连接相邻月份并闭合）
            const positions = animalData[animal].positions;
            for (let i = 0; i < positions.length; i++) {
                const nextIndex = (i + 1) % positions.length;
                entities[animal].lines.push(viewer.entities.add({
                    polyline: {
                        positions: [positions[i], positions[nextIndex]],
                        width: 3,
                        material: animalData[animal].color
                    },
                    properties: {
                        url: animalData[animal].url
                    }
                }));
            }
        });

        // 添加控制面板
        const controls = document.createElement('div');
        controls.style.position = 'absolute';
        controls.style.top = '100px';
        controls.style.left = '20px';
        controls.style.background = 'rgba(255,255,255,0.9)';
        controls.style.padding = '15px';
        controls.style.borderRadius = '8px';
        controls.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
        controls.style.fontFamily = 'Microsoft YaHei, sans-serif';
        controls.innerHTML = `
            <div style="margin-bottom:10px;">显示动物迁徙轨迹：</div>
            ${Object.keys(animalData).map(animal => `
                <label style="display:block;">
                    <input type="checkbox" checked data-animal="${animal}">
                    <span style="display:inline-block;width:12px;height:12px;background:${animalData[animal].color.toCssColorString()};margin-right:5px;"></span>
                    ${{
                        zebra: '斑马',
                        avocet: '反嘴鹬', 
                        stilt: '黑翅长脚鹬',
                        wildebeest: '角马',
                        robin: '美洲知更鸟'
                    }[animal]}
                </label>
            `).join('')}
        `;
        viewer.container.appendChild(controls);

        // 绑定复选框事件
        controls.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const animal = e.target.dataset.animal;
                const isChecked = e.target.checked;
                
                // 控制常规实体
                entities[animal].points.forEach(entity => entity.show = isChecked);
                entities[animal].lines.forEach(entity => entity.show = isChecked);
                
                // 特别处理跳转点
                if (entities[animal].jumpPoint) {
                    entities[animal].jumpPoint.show = isChecked;
                }
            });
        });

        // 添加时间轴控件和逻辑
        const timeline = document.createElement('div');
        timeline.style.position = 'absolute';
        timeline.style.bottom = '20px';
        timeline.style.left = '50%';
        timeline.style.transform = 'translateX(-50%)';
        timeline.style.background = 'rgba(255,255,255,0.9)';
        timeline.style.padding = '15px';
        timeline.style.borderRadius = '8px';
        timeline.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
        timeline.style.minWidth = '300px';
        timeline.innerHTML = `
            <div style="margin-bottom:10px; text-align:center;">迁徙时间轴</div>
            <input type="range" id="monthSlider" min="1" max="12" value="1" 
                   style="width:100%; margin-bottom:10px;">
            <div id="monthDisplay" style="text-align:center;">当前月份：1月</div>
        `;
        viewer.container.appendChild(timeline);

        // 添加信息显示面板
        const infoPanel = document.createElement('div');
        infoPanel.id = 'infoPanel';
        infoPanel.style.position = 'absolute';
        infoPanel.style.top = '100px';
        infoPanel.style.right = '100px';
        infoPanel.style.background = 'rgba(255,255,255,0.9)';
        infoPanel.style.padding = '15px';
        infoPanel.style.borderRadius = '8px';
        infoPanel.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
        infoPanel.style.fontFamily = 'Microsoft YaHei, sans-serif';
        infoPanel.innerHTML = `<div id="animalInfo">当前无选中动物</div>`;
        viewer.container.appendChild(infoPanel);

        // 添加影像展示点实体
        const imagePoint = viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(108.248, 42.321),
            point: {
                pixelSize: 14,
                color: Cesium.Color.PINK.withAlpha(0.8),
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 3,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            description: '点击查看影像'
        });

        // 添加图片弹窗HTML结构
        const imageModal = document.createElement('div');
        imageModal.id = 'imageModal';
        imageModal.style.display = 'none';
        imageModal.style.position = 'fixed';
        imageModal.style.zIndex = '1000';
        imageModal.style.left = '0';
        imageModal.style.top = '0';
        imageModal.style.width = '100%';
        imageModal.style.height = '100%';
        imageModal.style.backgroundColor = 'rgba(0,0,0,0.8)';
        
        const imageContent = document.createElement('div');
        imageContent.style.position = 'relative';
        imageContent.style.backgroundColor = '#fff';
        imageContent.style.margin = '2% auto';
        imageContent.style.padding = '15px';
        imageContent.style.width = '85%';
        imageContent.style.maxWidth = '1000px';
        imageContent.style.borderRadius = '8px';
        imageContent.style.maxHeight = '90vh';
        imageContent.style.overflow = 'auto';

        const imageCloseBtn = document.createElement('span');
        imageCloseBtn.className = 'close-btn';
        imageCloseBtn.innerHTML = '&times;';
        imageCloseBtn.onclick = closeImageModal;

        const imagePreview = document.createElement('img');
        imagePreview.id = 'imagePreview';
        imagePreview.style.width = '100%';
        imagePreview.style.height = 'auto';
        imagePreview.style.maxWidth = '90vw';
        imagePreview.style.maxHeight = '90vh';
        imagePreview.style.objectFit = 'contain';
        imagePreview.style.display = 'block';
        imagePreview.style.margin = '0 auto';

        imageContent.appendChild(imageCloseBtn);
        imageContent.appendChild(imagePreview);
        imageModal.appendChild(imageContent);
        document.body.appendChild(imageModal);

        // 图片弹窗控制函数
        function openImageModal() {
            document.getElementById('imageModal').style.display = 'block';
        }

        function closeImageModal() {
            document.getElementById('imageModal').style.display = 'none';
        }

        // 添加视频弹窗HTML结构
        const videoModal = document.createElement('div');
        videoModal.id = 'videoModal';
        videoModal.style.display = 'none';
        videoModal.style.position = 'fixed';
        videoModal.style.zIndex = '1000';
        videoModal.style.left = '0';
        videoModal.style.top = '0';
        videoModal.style.width = '100%';
        videoModal.style.height = '100%';
        videoModal.style.backgroundColor = 'rgba(0,0,0,0.8)';
        
        const videoContent = document.createElement('div');
        videoContent.style.position = 'relative';
        videoContent.style.backgroundColor = '#fff';
        videoContent.style.margin = '2% auto';
        videoContent.style.padding = '15px';
        videoContent.style.width = '85%';
        videoContent.style.maxWidth = '1000px';
        videoContent.style.borderRadius = '8px';
        videoContent.style.maxHeight = '90vh';
        videoContent.style.overflow = 'auto';

        const closeBtn = document.createElement('span');
        closeBtn.className = 'close-btn';
        closeBtn.innerHTML = '&times;';
        closeBtn.onclick = closeVideoModal;

        const videoPlayer = document.createElement('video');
        videoPlayer.id = 'mainVideo';
        videoPlayer.className = 'video-player';
        videoPlayer.style.width = '100%';
        videoPlayer.style.height = 'auto';
        videoPlayer.style.maxWidth = '90vw';
        videoPlayer.style.maxHeight = '90vh';
        videoPlayer.style.objectFit = 'contain';
        videoPlayer.style.display = 'block';
        videoPlayer.style.margin = '0 auto';
        videoPlayer.controls = true;
        videoPlayer.playsInline = true;
        videoPlayer.innerHTML = `
            <source src="" type="video/mp4">
            您的浏览器不支持视频播放
        `;

        videoContent.appendChild(closeBtn);
        videoContent.appendChild(videoPlayer);
        videoModal.appendChild(videoContent);
        document.body.appendChild(videoModal);

        // 视频弹窗控制函数
        function openVideoModal() {
            document.getElementById('videoModal').style.display = 'block';
            document.getElementById('mainVideo').play();
        }

        function closeVideoModal() {
            const modal = document.getElementById('videoModal');
            const video = document.getElementById('mainVideo');
            modal.style.display = 'none';
            video.pause();
            video.currentTime = 0;
        }

        // 点击模态框背景关闭
        document.addEventListener('click', function(event) {
            if (event.target === document.getElementById('videoModal')) {
                closeVideoModal();
            }
        });

        // 添加响应式样式
        const style = document.createElement('style');
        style.innerHTML = `
            @media (max-width: 768px) {
                .video-content {
                    width: 95% !important;
                    margin: 10px auto !important;
                    padding: 10px !important;
                }
                .video-player {
                    max-height: 70vh !important;
                }
                .close-btn {
                    right: 5px !important;
                    top: 5px !important;
                }
            }
        `;
        document.head.appendChild(style);

        const slider = document.getElementById('monthSlider');
        const monthDisplay = document.getElementById('monthDisplay');
        let highlightEntities = [];

        // 高亮颜色配置
        const highlightColors = {
            zebra: Cesium.Color.RED.withAlpha(0.9),
            avocet: Cesium.Color.CYAN.withAlpha(0.9),
            stilt: Cesium.Color.LIME.withAlpha(0.9),
            wildebeest: Cesium.Color.GOLD.withAlpha(0.9),
            robin: Cesium.Color.MAGENTA.withAlpha(0.9)
        };

        slider.addEventListener('input', function(e) {
            const month = parseInt(e.target.value);
            monthDisplay.textContent = `当前月份：${month}月`;
            updateHighlight(month - 1);

            // 更新信息面板
            const activeAnimals = Array.from(controls.querySelectorAll('input[type="checkbox"]:checked'))
                                    .map(checkbox => checkbox.dataset.animal);
            
            if (activeAnimals.length === 1) {
                const animal = activeAnimals[0];
                const positions = animalData[animal].positions;
                const monthIndex = month - 1;
                
                if (positions[monthIndex]) {
                    const cartographic = Cesium.Cartographic.fromCartesian(positions[monthIndex]);
                    const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
                    const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
                    
                    document.getElementById('animalInfo').innerHTML = `
                        ${getAnimalChineseName(animal)}，${month}月<br>
                        经度：${longitude}<br>
                        纬度：${latitude}
                    `;
                }
            } else {
                document.getElementById('animalInfo').textContent = "请选择单个动物查看详细信息";
            }
        });

        // 动物名称中英映射
        function getAnimalChineseName(animal) {
            return {
                zebra: '斑马',
                avocet: '反嘴鹬', 
                stilt: '黑翅长脚鹬',
                wildebeest: '角马',
                robin: '美洲知更鸟'
            }[animal];
        }

        // 跳转点点击事件处理
        viewer.screenSpaceEventHandler.setInputAction((click) => {
            const pickedObject = viewer.scene.pick(click.position);
            if (Cesium.defined(pickedObject)) {
                // 处理线实体点击
                if (pickedObject.id && pickedObject.id.properties && pickedObject.id.properties.url) {
                    window.location.href = pickedObject.id.properties.url.getValue();
                }
                // 处理跳转点点击
                else if (pickedObject.id === entities.wildebeest.jumpPoint) {
                    window.location.href = 'wildebeest1.html';
                } else if (pickedObject.id === entities.zebra.jumpPoint) {
                    window.location.href = 'zebra.html';
                }else if (pickedObject.id === entities.avocet.jumpPoint) {
                    window.location.href = 'avocet.html';
                }else if (pickedObject.id === entities.stilt.jumpPoint) {
                    window.location.href = 'stilt.html';
                }else if (pickedObject.id === entities.robin.jumpPoint) {
                    window.location.href = 'robin.html';
                } else if (pickedObject.id === entities.wildebeest.videoPoint) {
                    // 设置第一个视频路径（示例路径）
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/jiaomabanma.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                } else if (pickedObject.id === entities.wildebeest.videoPoint2) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/liebao.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                } else if (pickedObject.id === entities.wildebeest.videoPoint3) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/shizi1.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                } else if (pickedObject.id === entities.wildebeest.videoPoint4) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/changjinglu.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }else if (pickedObject.id === entities.wildebeest.videoPoint5) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/eyu.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }else if (pickedObject.id === entities.wildebeest.videoPoint6) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/guomalahe.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }else if (pickedObject.id === entities.wildebeest.videoPoint7) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/fanzuiyu.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }else if (pickedObject.id === entities.wildebeest.videoPoint8) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="../../../data/changjiaoyu.mp4?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }else if (pickedObject.id === entities.wildebeest.videoPoint9) {
                    const video = document.getElementById('mainVideo');
                    video.innerHTML = `
                        <source src="http://localhost:4000/3Dtrack/get_video/Himantopus?t=${Date.now()}" type="video/mp4">
                        您的浏览器不支持视频播放
                    `;
                    video.load();
                    video.play().catch(() => {});
                    openVideoModal();
                }

                // 新增影像展示点
                else if (pickedObject.id === imagePoint) {
                    document.getElementById('imagePreview').src = "../../../data/yu.png?t=" + Date.now();
                    openImageModal();
                }
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        function updateHighlight(monthIndex) {
            // 清除之前的高亮点
            highlightEntities.forEach(entity => viewer.entities.remove(entity));
            highlightEntities = [];

            // 获取当前选中的动物
            const activeAnimals = Array.from(controls.querySelectorAll('input[type="checkbox"]:checked'))
                                    .map(checkbox => checkbox.dataset.animal);

            activeAnimals.forEach(animal => {
                if (monthIndex < animalData[animal].positions.length) {
                    const position = animalData[animal].positions[monthIndex];
                    highlightEntities.push(viewer.entities.add({
                        position: position,
                        point: {
                            pixelSize: 16,  // 更大的尺寸
                            color: highlightColors[animal],
                            outlineColor: Cesium.Color.WHITE,
                            outlineWidth: 2
                        }
                    }));
                }
            });
        }
        document.addEventListener('DOMContentLoaded', function() {
            const imageModal = document.getElementById("uploadImageModal");
        const openImageModalBtn = document.getElementById("openImageModalBtn");
        const closeImageModalBtn = document.getElementById("closeImageModal");

        openImageModalBtn.onclick = function() {
            imageModal.style.display = "block";
        }

        closeImageModalBtn.onclick = function() {
            imageModal.style.display = "none";
        }

        window.onclick = function(event) {
            if (event.target == imageModal) {
                imageModal.style.display = "none";
            }
        }

        // 处理上传图片与地理信息
        document.getElementById("uploadImageBtn").onclick = async function() {
            const fileInput = document.getElementById('fileInput');
            const longitudeInput = document.getElementById('longitudeInput');
            const latitudeInput = document.getElementById('latitudeInput');

            if (fileInput.files.length === 0 || !longitudeInput.value || !latitudeInput.value) {
                alert('请填写所有信息');
                return;
            }

            const file = fileInput.files[0];
            const formData = new FormData();
            formData.append('species', 'test');
            formData.append('location_long', longitudeInput.value);
            formData.append('location_lat', latitudeInput.value);
            formData.append('photo', file);

            try {
                const response = await fetch('http://localhost:4000/knowledge_git/upload_best_photo_point', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    alert('上传成功！');
                    imageModal.style.display = "none";
                    fileInput.value = '';
                    longitudeInput.value = '';
                    latitudeInput.value = '';
                } else {
                    throw new Error('上传失败');
                }
            } catch (err) {
                console.error('上传失败:', err);
                alert('上传失败：' + err.message);
            }
        };

        // 打开与关闭 CSV 上传模态框
        const csvModal = document.getElementById("uploadCsvModal");
        const openCsvModalBtn = document.getElementById("openModalBtn");
        const closeCsvModalBtn = document.getElementById("closeCsvModal");

        openCsvModalBtn.onclick = function() {
            csvModal.style.display = "block";
        }

        closeCsvModalBtn.onclick = function() {
            csvModal.style.display = "none";
        }

        window.onclick = function(event) {
            if (event.target == csvModal) {
                csvModal.style.display = "none";
            }
        }

        // 处理上传 CSV 文件
        document.getElementById('csvUploadForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const speciesName = document.getElementById('speciesName').value;
            var speciesName1='unknown'+speciesName;
            const fileInput = document.getElementById('csvFile');
            const file = fileInput.files[0];
            const messageDiv = document.getElementById('csvMessage');

            if (file) {
                const formData = new FormData();
                formData.append('csvFile', file);

                messageDiv.innerHTML = '文件上传中...';

                fetch(`http://localhost:4000/upload-csv/${encodeURIComponent(speciesName1)}`, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    messageDiv.innerHTML = data.message || '文件上传成功！';
                    localStorage.setItem('importedtrackData', JSON.stringify(data.data));
                    console.log('数据已保存到 localStorage');
                })
                .catch(error => {
                    messageDiv.innerHTML = '上传失败：' + error.message;
                    console.error('错误:', error);
                });
            } else {
                messageDiv.innerHTML = '请先选择一个 CSV 文件。';
            }
        });

















// 初始化时设置全局点击事件处理（只需执行一次）
viewer.screenSpaceEventHandler.setInputAction((click) => {
  const pickedObject = viewer.scene.pick(click.position);
  if (Cesium.defined(pickedObject) && pickedObject.id instanceof Cesium.Entity) {
    const entity = pickedObject.id;
    if (entity.popupContent) { 
      openCustomPopup(entity.popupContent);
    }
  }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

// 获取摄影点数据的函数
async function fetchPhotographyPoints(speciesName) {
  try {
    const response = await fetch(`http://localhost:4000/2D/get_points/${speciesName}`);
    if (!response.ok) throw new Error('网络响应不正常');
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('获取摄影点数据失败:', error);
    throw error;
  }
}

// 清除所有摄影点实体（不影响其他实体）
function clearPhotographyPoints() {
  const allEntities = viewer.entities.values;
  // 倒序遍历避免删除时索引错乱
  for (let i = allEntities.length - 1; i >= 0; i--) {
    const entity = allEntities[i];
    // 通过 entityType 标识判断是否为摄影点
    if (entity.entityType === 'photography_point') {
      viewer.entities.remove(entity);
    }
  }
}

// 显示摄影点的主函数
async function displayPhotographyPoints(speciesName) {
  const loadingElement = document.getElementById('loading');
  loadingElement.style.display = 'block';

  try {
    const photographyPoints = await fetchPhotographyPoints(speciesName);
    console.log('Photography points:', photographyPoints);

    if (photographyPoints.length === 0) {
      loadingElement.innerHTML = '没有找到摄影点数据';
      loadingElement.style.color = 'red';
      return;
    }

    clearPhotographyPoints(); // 只清除摄影点，保留其他实体

    // 遍历所有摄影点添加实体
    photographyPoints.forEach(point => {
      const coordinates = Cesium.Cartesian3.fromDegrees(
        point.location.coordinates[0],
        point.location.coordinates[1]
      );

      // 处理图片数据
      let imgSrc = '';
      if (point.photo?.data instanceof Array) {
        const byteArray = new Uint8Array(point.photo.data);
        imgSrc = `data:image/jpeg;base64,${arrayBufferToBase64(byteArray)}`;
      } else {
        imgSrc = 'https://via.placeholder.com/300x200?text=No+Image';
      }

      // 构建弹窗内容
      const popupContent = `
        <strong>${point.speciesName}</strong><br>
        <img src="${imgSrc}" 
             onerror="this.src='https://via.placeholder.com/300x200?text=No+Image';" 
             style="max-width:300px; max-height:200px;"><br>
        创建时间: ${new Date(point.createdAt).toLocaleString()}
      `;

      // 添加实体并保存弹窗内容及类型标识
      viewer.entities.add({
        position: coordinates,
        point: {
          pixelSize: 10,
          color: Cesium.Color.RED
        },
        label: {
          text: '点击查看',
          font: '14px sans-serif',
          style: Cesium.LabelStyle.FILL,
          outlineWidth: 2,
          outlineColor: Cesium.Color.BLACK,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER
        },
        popupContent: popupContent,
        entityType: 'photography_point' // 关键：添加类型标识
      });
    });

    // 调整地图视角到摄影点范围
    if (photographyPoints.length > 0) {
      viewer.zoomTo(viewer.entities);
    }

  } catch (error) {
    loadingElement.innerHTML = '加载失败: ' + error.message;
    loadingElement.style.color = 'red';
  } finally {
    loadingElement.style.display = 'none';
  }
}

// 工具函数：二进制转Base64
function arrayBufferToBase64(buffer) {
  return window.btoa([...new Uint8Array(buffer)].map(b => String.fromCharCode(b)).join(''));
}

// 自定义弹窗函数
function openCustomPopup(content) {
  let popup = document.getElementById('custom-popup');
  if (!popup) {
    popup = document.createElement('div');
    popup.id = 'custom-popup';
    popup.style.cssText = `
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
      z-index: 1000;
      max-width: 500px;
      max-height: 400px;
      overflow: auto;
      display: none;
    `;

    const closeBtn = document.createElement('button');
    closeBtn.textContent = '×';
    closeBtn.style.cssText = `
      position: absolute;
      top: 5px;
      right: 10px;
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
    `;
    closeBtn.onclick = () => popup.style.display = 'none';

    const contentDiv = document.createElement('div');
    popup.append(closeBtn, contentDiv);
    document.body.appendChild(popup);
  }

  popup.querySelector('div').innerHTML = content;
  popup.style.display = 'block';
}

// 绑定物种选择事件
document.getElementById('speciesSelect').addEventListener('change', (e) => {
  if (e.target.value) displayPhotographyPoints(e.target.value);
});
});

    

    



    </script>

</body>
</html>
